<template>
	<view class="container">
		<!-- 已登录状态 -->
		<view v-if="isLogin">
			<view class="user-card">
				<view class="user-info">
					<view class="avatar">
						<image :src="userInfo.avatar || '/static/avatar.png'" mode="aspectFill"></image>
					</view>
					<view class="nickname">{{userInfo.nickName}}</view>
					<view class="user-desc">已记录{{userInfo.cycleCount}}个月经周期</view>
				</view>
				<view class="wave-bg"></view>
			</view>
			
			<view class="section-title">个人设置</view>
			<view class="menu-list">
				<!-- 月经提醒订阅按钮 -->
				<view class="menu-item" @click="requestSubscribeMessage">
					<view class="menu-icon">🔔</view>
					<view class="menu-title">
						月经提醒
						<view class="menu-description">点击订阅微信月经提醒</view>
					</view>
					<view class="menu-right">
						<view class="subscribe-status" :class="{ 'subscribed': hasSubscribed }">
							{{ hasSubscribed ? '已订阅' : '未订阅' }}
						</view>
					</view>
				</view>
				
				<!-- 贴心科普设置项 -->
				<view class="menu-item" @click="navigateTo('/pages/articles/articles')">
					<view class="menu-icon">📚</view>
					<view class="menu-title">贴心科普</view>
					<view class="menu-right">
						<view class="menu-badge" v-if="hasNewArticles">New</view>
						<wd-icon name="arrow-right" size="18"></wd-icon>
					</view>
				</view>
				
				<!-- 告诉男友设置项 -->
				<view class="menu-item" @click="showShareOptions">
					<view class="menu-icon">💕</view>
					<view class="menu-title">告诉男友</view>
					<view class="menu-right">
						<view class="share-icon">📤</view>
						<wd-icon name="arrow-right" size="18"></wd-icon>
					</view>
				</view>
			</view>
			
			<view class="section-title">系统设置</view>
			<view class="menu-list">
				<!-- 系统设置项 -->
				<view class="menu-item" @click="navigateTo('/pages/settings/settings')">
					<view class="menu-icon">⚙️</view>
					<view class="menu-title">经期设置</view>
					<view class="menu-right">
						<wd-icon name="arrow-right" size="18"></wd-icon>
					</view>
				</view>
						<!-- 帮助与反馈设置项 -->
				<button class="menu-item contact-button" open-type="contact" @contact="handleContact">
					<view class="menu-icon">❓</view>
					<view class="menu-title">联系客服</view>
					<view class="menu-right">
						<wd-icon name="arrow-right" size="18"></wd-icon>
					</view>
				</button>
				
				<!-- 退出登录 -->
				<view class="menu-item" @click="logout">
					<view class="menu-icon">🚪</view>
					<view class="menu-title">退出登录</view>
					<view class="menu-right">
						<wd-icon name="arrow-right" size="18"></wd-icon>
					</view>
				</view>
			</view>
		</view>
		
		<!-- 分享选项弹窗 -->
		<wd-action-sheet
			v-model="showShare"
			:actions="shareActions"
			title="选择分享方式"
			@select="onShareSelect"
		></wd-action-sheet>
		
		<!-- 提示组件 -->
		<wd-toast ref="toast"></wd-toast>
	</view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { onShareAppMessage } from '@dcloudio/uni-app'

// 登录状态
const isLogin = ref(false)

// 头像、昵称等信息
const userInfo = ref({
	nickName: '小粉红',
	cycleCount: 3,
	avatar: '/static/avatar.png'
})

// 功能设置状态
const hasNewArticles = ref(true)
const showShare = ref(false)
const toast = ref(null)
const hasSubscribed = ref(false)
const TEMPLATE_ID = 'M7hgSK9yXi_5W3JNzrL10G97XQLI99IWp2uk1ESV0iw' // 订阅消息模板ID

// 显示Toast提示
const showToast = (message) => {
	uni.showToast({
		title: message,
		icon: 'none',
		duration: 2000
	})
}

// 分享选项
const shareActions = [
	{ name: '生成关怀卡片', icon: 'picture-fill' },
	{ name: '发送微信消息', icon: 'chat' },
	{ name: '复制链接', icon: 'link' }
]

// 页面加载时检查登录状态
onMounted(() => {
	// 先检查是否登录
	const loginStatus = checkLoginStatus()
	// 如果登录了，加载用户信息
	if (loginStatus) {
		loadUserInfo()
		
		// 检查是否已订阅
		checkSubscriptionStatus()
	}
})

// 检查登录状态
const checkLoginStatus = () => {
	const loginFlag = uni.getStorageSync('isLogin')
	if (loginFlag !== 'true') {
		console.log('用户未登录，跳转到登录页')
		uni.navigateTo({
			url: '/pages/login/login'
		})
		return false
	}
	isLogin.value = true
	return true
}

// 加载用户信息
const loadUserInfo = () => {
	try {
		const userData = uni.getStorageSync('userInfo')
		
		if (userData) {
			userInfo.value = JSON.parse(userData)
			console.log('已加载用户信息：', userInfo.value)
		}
	} catch (e) {
		console.error('获取用户信息失败', e)
	}
}

// 检查订阅状态
const checkSubscriptionStatus = () => {
	try {
		// 从本地存储获取订阅状态
		const subscribed = uni.getStorageSync('hasSubscribedMessage')
		hasSubscribed.value = subscribed === 'true'
	} catch (e) {
		console.error('获取订阅状态失败', e)
	}
}

// 请求订阅消息
const requestSubscribeMessage = async () => {
	try {
		// 调用微信订阅消息API
		const res = await uni.requestSubscribeMessage({
			tmplIds: [TEMPLATE_ID]
		})
		
		console.log('订阅消息响应:', res)
		
		if (res.errMsg === 'requestSubscribeMessage:ok') {
			// 检查模板消息的订阅结果
			if (res[TEMPLATE_ID] === 'accept') {
				// 用户接受了订阅
				hasSubscribed.value = true
				uni.setStorageSync('hasSubscribedMessage', 'true')
				showToast('订阅成功，将在经期前通知您')
				
				// 获取openid
				await getOpenid()
			} else if (res[TEMPLATE_ID] === 'reject') {
				// 用户拒绝了订阅
				hasSubscribed.value = false
				uni.setStorageSync('hasSubscribedMessage', 'false')
				showToast('您已拒绝订阅，将不会收到经期提醒')
			} else {
				showToast('订阅状态未知，请重试')
			}
		} else {
			showToast('订阅请求失败，请重试')
		}
	} catch (error) {
		console.error('请求订阅消息出错:', error)
		showToast('订阅请求异常，请重试')
	}
}

// 获取用户openid
const getOpenid = async () => {
	try {
		console.log('正在获取用户openid...')
		
		// 初始化云环境
		await initCloud()
		
		// 调用获取openid的云函数
		const result = await uniCloud.callFunction({
			name: 'getOpenid',
			data: {
				userId: userInfo.value.userId || userInfo.value._id || 'unknown_user', // 传递userId参数
				isTestEnv: true // 标记为测试环境
			}
		})
		
		console.log('getOpenid返回结果:', result)
		
		if (result.result && result.result.code === 0 && result.result.openid) {
			const openid = result.result.openid
			console.log('获取到openid:', openid)
			uni.setStorageSync('openid', openid)
			return openid
		} else {
			const errorMsg = result.result && result.result.message ? result.result.message : '未知错误'
			console.error('获取openid失败:', result.result, '错误信息:', errorMsg)
			showToast('获取openid失败: ' + errorMsg)
			return ''
		}
	} catch (error) {
		console.error('获取openid错误:', error)
		showToast('获取openid出错: ' + error.message)
		return ''
	}
}

// 初始化云环境
const initCloud = () => {
	return new Promise((resolve, reject) => {
		const spaceId = 'mp-f9881352-2084-4a8f-b3ef-b52bdf18452c'
		const clientSecret = '7ubwCOOf8ZdSFMOUL2pd1A=='
		
		uni.showLoading({
			title: '加载中'
		})
		
		uniCloud.init({
			spaceId,
			clientSecret,
			provider: 'aliyun'
		})
		
		uni.hideLoading()
		resolve()
	})
}

// 退出登录
const logout = () => {
	uni.showModal({
		title: '提示',
		content: '确定要退出登录吗？',
		success: (res) => {
			if (res.confirm) {
				// 清除登录状态和用户信息
				uni.removeStorageSync('isLogin')
				uni.removeStorageSync('userInfo')
				uni.removeStorageSync('token')
				uni.removeStorageSync('userId')
				uni.removeStorageSync('openid')
				uni.removeStorageSync('hasSubscribedMessage')
				
				// 重置登录状态
				isLogin.value = false
				
				// 跳转到登录页
				uni.navigateTo({
					url: '/pages/login/login'
				})
			}
		}
	})
}

// 显示分享选项
const showShareOptions = () => {
	showShare.value = true
}

// 处理分享选择
const onShareSelect = (item) => {
	console.log('选择分享方式：', item.name)
	
	if (item.name === '生成关怀卡片') {
		setTimeout(() => {
			showToast('关怀卡片已生成')
		}, 1000)
	} else if (item.name === '发送微信消息') {
		// 这里调用分享API
		uni.share({
			provider: 'weixin',
			type: 0,
			title: '我的经期日历',
			summary: '我已经开始使用粉红日记，方便你了解我的日程安排~',
			imageUrl: '/static/share.png',
			success: function () {
				console.log('分享成功')
			}
		})
	} else if (item.name === '复制链接') {
		uni.setClipboardData({
			data: 'https://pink-diary.example.com/share?id=12345',
			success: function () {
				showToast('链接已复制')
			}
		})
	}
}

// 处理客服会话
const handleContact = (e) => {
	console.log('客服会话事件：', e.detail)
	// 可以在这里记录用户咨询事件
}

// 页面导航
const navigateTo = (url) => {
	uni.navigateTo({ url })
}

onShareAppMessage(() => {
	return {
		title: '粉色日记',
		path: '/pages/login/login'
	}
})
</script>

<style lang="scss" scoped>
.container {
	padding: 0 0 40px;
	max-width: 375px;
	margin: 0 auto;
	background-color: $background-color;
}

.user-card {
	background: linear-gradient(135deg, $brand-theme-color 0%, $brand-theme-color-light 100%);
	padding: 40px 20px;
	position: relative;
	overflow: hidden;
}

.wave-bg {
	position: absolute;
	bottom: 0;
	left: 0;
	width: 100%;
	height: 30px;
	background: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 1200 120' preserveAspectRatio='none'%3E%3Cpath d='M0,0V46.29c47.79,22.2,103.59,32.17,158,28,70.36-5.37,136.33-33.31,206.8-37.5C438.64,32.43,512.34,53.67,583,72.05c69.27,18,138.3,24.88,209.4,13.08,36.15-6,69.85-17.84,104.45-29.34C989.49,25,1113-14.29,1200,52.47V0Z' opacity='.25' fill='%23ffffff'/%3E%3Cpath d='M0,0V15.81C13,36.92,27.64,56.86,47.69,72.05,99.41,111.27,165,111,224.58,91.58c31.15-10.15,60.09-26.07,89.67-39.8,40.92-19,84.73-46,130.83-49.67,36.26-2.85,70.9,9.42,98.6,31.56,31.77,25.39,62.32,62,103.63,73,40.44,10.79,81.35-6.69,119.13-24.28s75.16-39,116.92-43.05c59.73-5.85,113.28,22.88,168.9,38.84,30.2,8.66,59,6.17,87.09-7.5,22.43-10.89,48-26.93,60.65-49.24V0Z' opacity='.5' fill='%23ffffff'/%3E%3Cpath d='M0,0V5.63C149.93,59,314.09,71.32,475.83,42.57c43-7.64,84.23-20.12,127.61-26.46,59-8.63,112.48,12.24,165.56,35.4C827.93,77.22,886,95.24,951.2,90c86.53-7,172.46-45.71,248.8-84.81V0Z' fill='%23ffffff'/%3E%3C/svg%3E") no-repeat;
	background-size: cover;
}

.user-info {
	display: flex;
	flex-direction: column;
	align-items: center;
	position: relative;
	z-index: 1;
}

.avatar {
	width: 120px;
	height: 120px;
	border-radius: 60px;
	border: 4px solid white;
	box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
	margin-bottom: 16px;
	background-color: #f9f9f9;
	display: flex;
	align-items: center;
	justify-content: center;
	overflow: hidden;
}

.avatar image {
	width: 100%;
	height: 100%;
}

.nickname {
	font-size: 20px;
	font-weight: bold;
	color: white;
	margin-bottom: 8px;
	text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.user-desc {
	font-size: 14px;
	color: rgba(255, 255, 255, 0.9);
}

.section-title {
	padding: 16px 16px 8px;
	font-size: 14px;
	color: #666;
}

.menu-list {
	background-color: white;
	border-radius: 16px;
	margin: 0 16px 16px;
	overflow: hidden;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.menu-item {
	display: flex;
	align-items: center;
	padding: 16px;
	border-bottom: 1px solid #f5f5f5;
	position: relative;
}

.menu-item:last-child {
	border-bottom: none;
}

.menu-icon {
	width: 24px;
	height: 24px;
	display: flex;
	align-items: center;
	justify-content: center;
	margin-right: 12px;
	font-size: 18px;
	color: var(--primary-color);
}

.menu-title {
	flex: 1;
	font-size: 16px;
	color: #333;
}

.menu-right {
	display: flex;
	align-items: center;
}

.menu-description {
	font-size: 12px;
	color: #999;
	margin-top: 4px;
}

.menu-badge {
	background-color: var(--primary-color);
	color: white;
	font-size: 10px;
	border-radius: 10px;
	padding: 2px 6px;
	margin-right: 8px;
}

.share-icon {
	font-size: 18px;
	color: var(--primary-color);
	margin-right: 4px;
}

.contact-button {
	background: none !important;
	margin: 0 !important;
	padding: 16px !important;
	line-height: inherit !important;
	border: none !important;
	text-align: left !important;
	width: 100% !important;
	height: auto !important;
	display: flex !important;
	align-items: center !important;
	font-size: inherit !important;
	color: inherit !important;
	font-weight: normal !important;
	border-bottom: 1px solid #f5f5f5 !important;
}

.contact-button::after {
	border: none !important;
}

.contact-button:last-child {
	border-bottom: none !important;
}

.subscribe-status {
	padding: 4px 8px;
	border-radius: 12px;
	font-size: 12px;
	background-color: #f5f5f5;
	color: #666;
	margin-right: 8px;
}

.subscribe-status.subscribed {
	background-color: $brand-theme-color;
	color: white;
}
</style>
